package com.emm.yixun.common.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import com.github.sd4324530.fastexcel.annotation.MapperCell;

public class ExcelUtils {
    /**
     * 将数据写入excel文件
     *
     */
    public static <T> HSSFWorkbook createExcel(List<T> list, String sheetName) {
    	HSSFWorkbook wb = new HSSFWorkbook();  
    	HSSFSheet sheet = wb.createSheet(sheetName);  
        if (null != list && !list.isEmpty()) {
            T test = list.get(0);
            Map<String, Field> fieldMap = new HashMap<String, Field>();
            Map<Integer, String> titleMap = new TreeMap<Integer, String>();
            Field[] fields = test.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (field.isAnnotationPresent(MapperCell.class)) {
                    MapperCell mapperCell = field.getAnnotation(MapperCell.class);
                    fieldMap.put(mapperCell.cellName(), field);
                    titleMap.put(mapperCell.order(), mapperCell.cellName());
                }
            }
            try {
                Collection<String> values = titleMap.values();
                String[] s = new String[values.size()];
                values.toArray(s);
                //生成标题行
                Row titleRow = sheet.createRow(0);
                for (int i = 0; i < s.length; i++) {
                    Cell cell = titleRow.createCell(i);
                    cell.setCellValue(s[i]);
                }
                //生成数据行
                for (int i = 0, length = list.size(); i < length; i++) {
                    Row row = sheet.createRow(i + 1);
                    for (int j = 0; j < s.length; j++) {
                        Cell cell = row.createCell(j);
                        for (Map.Entry<String, Field> data : fieldMap.entrySet()) {
                            if (data.getKey().equals(s[j])) {
                                Field field = data.getValue();
                                field.setAccessible(true);
                                if(null!=field.get(list.get(i))){
                                	cell.setCellValue(field.get(list.get(i)).toString());
                                }else{
                                	cell.setCellValue("");
                                }
                                break;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return wb;
    }
}
